1.code
import React, { useState } from 'react';
const TodoList = () => {
const [tasks, setTasks] = useState([]);
const [newTask, setNewTask] = useState('');
const addTask = () => {
if (newTask.trim() !== '') {
setTasks([...tasks, { text: newTask, completed: false }]);
setNewTask('');
}
};
const deleteTask = (index) => {
const updatedTasks = [...tasks];
updatedTasks.splice(index, 1);
setTasks(updatedTasks);
};
const toggleCompletion = (index) => {
const updatedTasks = [...tasks];
updatedTasks[index].completed = !updatedTasks[index].completed;
setTasks(updatedTasks);
};
return (
<div>
<h1>Todo List</h1>
<div>
<input
type="text"
placeholder="Add a new task"
value={newTask}
onChange={(e) => setNewTask(e.target.value)}
/>
<button onClick={addTask}>Add</button>
</div>
<ul>
{tasks.map((task, index) => (
<li key={index}>
<input
type="checkbox"
checked={task.completed}
onChange={() => toggleCompletion(index)}
/>
{task.text}
<button onClick={() => deleteTask(index)}>Delete</button>
</li>
))}
</ul>
</div>
);
};
export default TodoList;
2.實作